package com.ruifu.doc.utils;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.ruifu.doc.conf.FileConfig;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Component
public class FastDFSClient {
    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FileConfig fileConfig;

    /**
     * 文件上传返回地址
     * @param file
     * @return
     * @throws IOException
     */
    public StorePath uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile((InputStream) file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return storePath;
    }

    /**
     * 封装文件完整URL地址
     *
     * @param fileUrl 存储在fastDFS上的唯一标识
     * @return
     */
    public String getResAccessUrl(String fileUrl) {
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        String newPath = path.substring(path.indexOf("/")+ 1);
        return fileConfig.getFileServerUrl() + newPath;
    }

    /**
     * 下载文件
     *
     * @param fileUrl
     * @throws Exception
     */
    public void downloadFile(String fileUrl, HttpServletResponse response) throws Exception {
        // 将数据写入输出流
        try {
            // 根据文件标识下载文件
            String group = fileUrl.substring(0, fileUrl.indexOf("/"));
            String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
            DownloadByteArray downloadByteArray = new DownloadByteArray();
            byte[] content = storageClient.downloadFile(group, path, downloadByteArray);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(content);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除文件
     *
     * @param fileUrl
     * @throws Exception
     */
    public void deleteFile(String fileUrl) throws Exception {
        // 根据文件标志删除文件
        storageClient.deleteFile(fileUrl);
    }

    /**
     * 获取文件byte[]
     *
     * @param fileUrl
     * @throws Exception
     */
    public byte[] copyFile(String fileUrl) throws Exception {
        // 根据文件标识从文件服务器获取文件数组
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        return storageClient.downloadFile(group, path, downloadByteArray);
    }



}
